﻿using Apps.Common;
using Apps.Models;
using Apps.Web.Core;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Apps.Web.Areas.RC.Controllers
{
    public class SampleInfoController : BaseController
    {
        [Dependency]
        public BLL.RC.RCSAMPLINGBLL m_BLL { get; set; }
        ValidationErrors errors = new ValidationErrors();

        [SupportFilter]
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [SupportFilter(ActionName = "Index")]
        public JsonResult GetList(GridPager pager, string BATCH_CODE, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME, string MATERIEL_NAME = "")
        {
            var list = m_BLL.GetSampleInfo(ref pager, BATCH_CODE, SAMPLING_BEGIN_TIME, SAMPLING_END_TIME, MATERIEL_NAME);
            GridRows<SampleInfoModel> grs = new GridRows<SampleInfoModel>();
            grs.rows = list;
            grs.total = pager.totalRows;
            return Json(grs);
        }

        #region 导出导入
    
        [HttpPost]
        [SupportFilter(ActionName = "Export")]
        public JsonResult CheckExportData(string BATCH_CODE, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME, string MATERIEL_NAME = "")
        {
            var list = m_BLL.GetSampleInfo(ref GridPager.NotPage, BATCH_CODE, SAMPLING_BEGIN_TIME, SAMPLING_END_TIME, MATERIEL_NAME);
            if (list.Count().Equals(0))
            {
                return Json(JsonHandler.CreateMessage(0, "没有可以导出的数据"));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(1, "可以导出"));
            }
        }
        [SupportFilter]
        public ActionResult Export(string BATCH_CODE, string SAMPLING_BEGIN_TIME, string SAMPLING_END_TIME, string MATERIEL_NAME = "")
        {
            var list = m_BLL.GetSampleInfo(ref GridPager.NotPage, BATCH_CODE, SAMPLING_BEGIN_TIME, SAMPLING_END_TIME, MATERIEL_NAME);
            JArray jObjects = new JArray();
            foreach (var item in list)
            {
                var jo = new JObject();
                jo.Add("批次号", item.BATCH_CODE);
                jo.Add("样桶号", item.SAMPLE_PAIL);
                jo.Add("采样编码", item.SAMPLE_CODE);
                jo.Add("最后时间", item.SAMPLING_END_TIME);
                jo.Add("车数", item.SCount);
                jObjects.Add(jo);
            }
            var dt = JsonConvert.DeserializeObject<DataTable>(jObjects.ToString());
            var exportFileName = string.Concat(
                "入厂采样样品信息",
                DateTime.Now.ToString("yyyyMMdd"),
                ".xlsx");
            return new ExportExcelResult
            {
                SheetName = "Sheet1",
                FileName = exportFileName,
                ExportData = dt
            };
        }
        #endregion
    }
}